import { ipcMain, dialog } from 'electron';
import ffmpeg from 'fluent-ffmpeg';
import path from 'node:path';
import fs from 'node:fs';
import { fileURLToPath } from 'node:url';

// 配置 ffmpeg 路径为系统安装路径
ffmpeg.setFfmpegPath('/usr/local/bin/ffmpeg');

// 确保输出目录存在
const ensureOutputDir = () => {
  const outputDir = path.join(process.env.APP_ROOT || '', 'output');
  if (!fs.existsSync(outputDir)) {
    fs.mkdirSync(outputDir, { recursive: true });
  }
  return outputDir;
};

// 初始化视频处理相关的IPC通信
export const initVideoProcessor = () => {
  // 处理选择保存路径的请求
  ipcMain.handle('select-save-path', async () => {
    const result = await dialog.showSaveDialog({
      title: '选择视频保存位置',
      defaultPath: path.join(process.env.APP_ROOT || '', 'output'),
      filters: [{ name: '视频文件', extensions: ['mp4'] }],
    });
    return result.filePath;
  });

  // 获取视频元数据
  const getVideoMetadata = (filePath: string): Promise<any> => {
    return new Promise((resolve, reject) => {
      ffmpeg.ffprobe(filePath, (err, metadata) => {
        if (err) reject(err);
        else resolve(metadata);
      });
    });
  };

  // 获取文件大小（以MB为单位）
  const getFileSize = (filePath: string): number => {
    const stats = fs.statSync(filePath);
    return Number((stats.size / (1024 * 1024)).toFixed(2));
  };

  // 处理视频压缩请求
  ipcMain.handle('compress-video', async (event, filePath, outputPath) => {
    try {
      // 确保输出目录存在
      const outputDir = path.dirname(outputPath);
      if (!fs.existsSync(outputDir)) {
        fs.mkdirSync(outputDir, { recursive: true });
      }

      // 获取原视频的元数据和文件大小
      const originalMetadata = await getVideoMetadata(filePath);
      
      // 检查视频流是否存在
      if (!originalMetadata.streams || !originalMetadata.streams.length) {
        throw new Error('无效的视频文件：未找到视频流');
      }

      // 检查视频流的基本属性
      const videoStream = originalMetadata.streams.find(stream => stream.codec_type === 'video');
      if (!videoStream) {
        throw new Error('无效的视频文件：未找到视频编码流');
      }

      const originalSize = getFileSize(filePath);
      const originalResolution = `${videoStream.width}x${videoStream.height}`;
      const originalBitrate = Math.round(originalMetadata.format.bit_rate / 1000);

      return new Promise((resolve, reject) => {
        let progress = 0;

        ffmpeg(filePath)
          .videoCodec('libx264')
          .size('1280x?') // 设置宽度为1280，高度自适应
          .videoBitrate('1000k')
          .audioCodec('aac') // 添加音频编码设置
          .audioBitrate('128k') // 设置音频比特率
          .on('progress', (info) => {
            progress = Math.round(info.percent);
            event.sender.send('compression-progress', progress);
          })
          .on('end', async () => {
            try {
              // 获取压缩后视频的元数据和文件大小
              const compressedMetadata = await getVideoMetadata(outputPath);
              
              // 验证压缩后的文件
              if (!compressedMetadata.streams || !compressedMetadata.streams.length) {
                throw new Error('压缩后的视频文件无效');
              }

              const compressedVideoStream = compressedMetadata.streams.find(stream => stream.codec_type === 'video');
              if (!compressedVideoStream) {
                throw new Error('压缩后的视频文件中未找到视频流');
              }

              const compressedSize = getFileSize(outputPath);
              const compressedResolution = `${compressedVideoStream.width}x${compressedVideoStream.height}`;
              const compressedBitrate = Math.round(compressedMetadata.format.bit_rate / 1000);

              resolve({
                success: true,
                outputPath,
                fileName: path.basename(outputPath),
                comparison: {
                  original: {
                    size: originalSize,
                    resolution: originalResolution,
                    bitrate: originalBitrate
                  },
                  compressed: {
                    size: compressedSize,
                    resolution: compressedResolution,
                    bitrate: compressedBitrate
                  },
                  compressionRatio: Number((((originalSize - compressedSize) / originalSize) * 100).toFixed(2))
                }
              });
            } catch (err) {
              // 如果压缩后的文件处理失败，尝试删除可能已经生成的文件
              try {
                if (fs.existsSync(outputPath)) {
                  fs.unlinkSync(outputPath);
                }
              } catch (deleteErr) {
                console.error('清理失败的压缩文件时出错:', deleteErr);
              }
              reject({
                success: false,
                error: '获取压缩后视频信息失败: ' + err.message
              });
            }
          })
          .on('error', (err) => {
            // 发生错误时清理可能已经生成的文件
            try {
              if (fs.existsSync(outputPath)) {
                fs.unlinkSync(outputPath);
              }
            } catch (deleteErr) {
              console.error('清理失败的压缩文件时出错:', deleteErr);
            }
            reject({
              success: false,
              error: err.message
            });
          })
          .save(outputPath);
      });
    } catch (error) {
      return {
        success: false,
        error: error.message
      };
    }
  });
};